package ams.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import ams.dao.IBaseDao;
import ams.model.dto.ExecResult;
import ams.model.entity.Rights;
import ams.model.entity.Role;
import ams.model.entity.User;
import ams.model.entity.UserRole;

@Service("userService")
public class UserService implements IUserService {

	@Autowired
	private IBaseDao<User> userDao;
	
	@Autowired
	private IBaseDao<Role> roleDao;
	
	@Autowired
	private IBaseDao<UserRole> userRoleDao;
	
	@Autowired
	private IBaseDao<Rights> rightsDao;


	@Override
	public ExecResult add(User user) {
		ExecResult execResult = new ExecResult();
		List<String> message = new ArrayList<>();

		Long sameEmailcount = null;
		Long sameTelcount = null;

		Long sameNamecount = userDao.count("select count(*) from User u where u.name = ? ",
				new Object[] { user.getName() });
		Long sameCodecount = userDao.count("select count(*) from User u where u.code = ? ",
				new Object[] { user.getCode() });
		Long sameAccountcount = userDao.count("select count(*) from User u where u.account = ? ",
				new Object[] { user.getAccount() });

		if (user.getEmail() != null) {
			sameEmailcount = userDao.count("select count(*) from User u where u.email = ? ",
					new Object[] { user.getEmail() });
		}
		if (user.getTel() != null) {
			sameTelcount = userDao.count("select count(*) from User u where u.tel = ? ",
					new Object[] { user.getTel() });
		}

		if (sameNamecount != 0) {
			execResult.setSuccess(false);
			message.add("用户名称重复！");
		}
		if (sameCodecount != 0) {
			execResult.setSuccess(false);
			message.add("用户编码重复！");
		}
		if (sameAccountcount != 0) {
			execResult.setSuccess(false);
			message.add("用户账号重复！");
		}
		if (sameEmailcount != 0) {
			execResult.setSuccess(false);
			message.add("用户邮件重复！");
		}
		if (sameTelcount != 0) {
			execResult.setSuccess(false);
			message.add("用户电话重复！");
		}

		if (sameNamecount == 0 && sameCodecount == 0 && sameAccountcount == 0
				&& (sameEmailcount == null || sameEmailcount == 0) && (sameTelcount == null || sameTelcount == 0)) {

			userDao.save(user);
			execResult.setSuccess(true);

		}
		execResult.setMessage(message);

		return execResult;
	}

	@Override
	public ExecResult update(User user) {
		ExecResult execResult = new ExecResult();
		List<String> message = new ArrayList<>();

		Long sameEmailcount = null;
		Long sameTelcount = null;

		Long sameNamecount = userDao.count("select count(*) from User u where u.name = ? and u.id != ? ",
				new Object[] { user.getName(), user.getId() });
		Long sameCodecount = userDao.count("select count(*) from User u where u.code = ? and u.id != ?  ",
				new Object[] { user.getCode(), user.getId() });
		Long sameAccountcount = userDao.count("select count(*) from User u where u.account = ? and u.id != ?  ",
				new Object[] { user.getAccount(), user.getId() });

		if (user.getEmail() != null) {
			sameEmailcount = userDao.count("select count(*) from User u where u.email = ? and u.id != ?  ",
					new Object[] { user.getEmail(), user.getId() });
		}
		if (user.getTel() != null) {
			sameTelcount = userDao.count("select count(*) from User u where u.tel = ? and u.id != ? ",
					new Object[] { user.getTel(), user.getId() });
		}

		if (sameNamecount != 0) {
			execResult.setSuccess(false);
			message.add("用户名称重复！");
		}
		if (sameCodecount != 0) {
			execResult.setSuccess(false);
			message.add("用户编码重复！");
		}
		if (sameAccountcount != 0) {
			execResult.setSuccess(false);
			message.add("用户账号重复！");
		}
		if (sameEmailcount != 0) {
			execResult.setSuccess(false);
			message.add("用户邮件重复！");
		}
		if (sameTelcount != 0) {
			execResult.setSuccess(false);
			message.add("用户电话重复！");
		}

		if (sameNamecount == 0 && sameCodecount == 0 && sameAccountcount == 0
				&& (sameEmailcount == null || sameEmailcount == 0) && (sameTelcount == null || sameTelcount == 0)) {

			userDao.update(user);
			execResult.setSuccess(true);

		}
		execResult.setMessage(message);

		return execResult;
	}

	@Override
	public ExecResult delete(List<Integer> idList) {
		ExecResult execResult = new ExecResult();
		Map<String, Object> paramMap = new HashMap<>();
		paramMap.put("idList", idList);
		String delUserRoleHql = "delete from UserRole ur where ur.user.id in (:idList)";
		String delUserHql = "delete from User u where u.id in (:idList)";
		//先删除用户角色关系
		userRoleDao.executeHql(delUserRoleHql, paramMap);
		//再删除用户（hql的delete无法级联删除，只能用session.delete()可以）
		userDao.executeHql(delUserHql, paramMap);
		execResult.setSuccess(true);
		return execResult;
	}

	@Override
	public List<User> userPage(Integer page, Integer rows) {
		List<User> userList = new ArrayList<>();
		userList = userDao.Find("from User u ", page, rows);
		return userList;
	}

	@Override
	public Long totalCount() {
		return userDao.count("select count(*) from User");
	}

	@Override
	public ExecResult setUserRole(Integer userId, List<Integer> roleIdList) {
		ExecResult execResult = new ExecResult();
		userRoleDao.executeHql("delete from UserRole ur where ur.user.id = ? ", new Object[] { userId });
		//把所有待插入的记录拼接成一个sql记录语句
		StringBuilder insertUserRoleSql = new StringBuilder();
		insertUserRoleSql.append("insert into t_user_role (user_id,role_id) values ");
		for(Integer roleId : roleIdList){
			insertUserRoleSql.append("(");
			insertUserRoleSql.append(userId);
			insertUserRoleSql.append(",");
			insertUserRoleSql.append(roleId);
			insertUserRoleSql.append("),");
		}
		if(roleIdList.size() != 0){
			userRoleDao.executeBySQL(insertUserRoleSql.substring(0, insertUserRoleSql.length()-1));
		}
		execResult.setSuccess(true);
		return execResult;
	}

	@Override
	public List<Role> getUserRole(Integer userId) {
		String hql = "select r from User u "
				+ "left join u.userRole ur "
				+ "left join ur.role r "
				+ "where u.id = ?";
		List<Role> roleList = roleDao.Find(hql , new Object[]{userId});
		return roleList;
	}

	
	@Override
	public List<Rights> getUserRights(String account) {
		String hql = "select rigths from User u "
				+ "inner join u.userRole ur "
				+ "inner join ur.role r "
				+ "inner join r.roleRights rr "
				+ "inner join rr.rights rigths "
				+ "where u.account = ? ";
		List<Rights> rightsList =  rightsDao.Find(hql, new Object[]{account});
		return rightsList;
		
	}

}
